package main

import (
	"Godemo/W1/demo/Socket/Web_demo/impl"
	"encoding/json"
	"fmt"
	"github.com/gorilla/websocket"
	"net/http"
	"time"
)

var (
	upgrader = websocket.Upgrader{
		// 允许跨域请求
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}
	req = 0
)

type user struct {
	Name string `json:"name"`
	Age int `json:"age"`
}

func wsHandle(w http.ResponseWriter, r *http.Request) {
	values := r.URL.Query()
	a := values["test"][0]
	fmt.Println(a)
	webConn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		return
	}

	user := user{
		Name: "aaa",
		Age: 10,
	}

	data, err := json.Marshal(user)
	if err != nil {
		fmt.Println(err)
	}

	conn, err := impl.InitConnection(webConn)
	if err != nil {
		goto ERR
	}

	go func() {
		for {
			err := conn.WriteMessage([]byte("heart beat"))
			if err != nil {
				req++
				fmt.Println(req)
				return
			}
			time.Sleep(1 * time.Second)
		}
	}()

	if err := conn.WriteMessage(data); err != nil {
		fmt.Println(err)
	}


	for {
		data, err := conn.ReadMessage()
		if err != nil {
			goto ERR
		}

		if err := conn.WriteMessage(data); err != nil {
			goto ERR
		}
	}

ERR:
	// TODO:关闭连接的操作
	conn.Close()

}

func main() {
	http.HandleFunc("/ws", wsHandle)

	_ = http.ListenAndServe("0.0.0.0:7777", nil)
}
